<template>
  <el-row :gutter="20">
    <el-col :xs="24" :sm="24" :lg="8" class="col-item">
      <el-card class="box-card" shadow="always">
        <div slot="header">
          <span>个人资料</span>
        </div>

        <ul>
          <li class="item clearfix">
            <user-avatar :circleUrl="url" :size="avatarSize" @handleAvatarSuccess="handleAvatarSuccess"/>
          </li>
          <li class="item clearfix">
            <span class="floatLeft"><i class="fa fa-user"/> 登录名称：</span>
            <span class="floatRight" v-text="data.userName">admin</span></li>
          <li class="item clearfix">
            <span class="floatLeft"><i class="fa fa-phone"/> 手机号码：</span>
            <span class="floatRight" v-text="data.phoneNumber">15888888888</span>
          </li>
          <li class="item clearfix">
            <span class="floatLeft"><i class="fa fa-group"/> 所属部门：</span>
            <span class="floatRight" v-text="deptAndPost.deptAndPostName" :title="deptAndPost.title">研发部门 / 董事长</span>
          </li>
          <li class="item clearfix">
            <span class="floatLeft"><i class="fa fa-envelope-o"/> 邮箱地址：</span>
            <span class="floatRight" v-text="data.email">novel@163.com</span>
          </li>
          <li class="item clearfix">
            <span class="floatLeft"><i class="fa fa-calendar"/> 创建时间：</span>
            <span class="floatRight" v-text="data.createTime">2018-03-16</span>
          </li>
        </ul>
      </el-card>
    </el-col>
    <el-col :xs="24" :sm="24" :lg="16" class="col-item">
      <el-card class="box-card" shadow="always">
        <div slot="header">
          <span>基本资料</span>
        </div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基本资料" name="userInfo" class="userInfo">
            <el-form :model="userModel" ref="userInfoForm" :rules="userInfoRules" label-width="80px"
                     size="small">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="userModel.name" prefix-icon="fa fa-user" placeholder="姓名"/>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="userModel.email" prefix-icon="fa fa-envelope-o"
                          placeholder="邮箱"/>
              </el-form-item>
              <el-form-item label="手机" prop="phoneNumber">
                <el-input v-model="userModel.phoneNumber" prefix-icon="fa fa-phone"
                          placeholder="手机"/>
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-select value="" v-model="userModel.sex" placeholder="性别">
                  <el-option label="男" value="0"/>
                  <el-option label="女" value="1"/>
                  <el-option label="保密" value="2"/>
                </el-select>
              </el-form-item>
            </el-form>
            <div class="bottom">
              <el-button @click="closeProfile" size="medium" icon="fa fa-reply-all"> 关 闭</el-button>
              <el-button type="primary" @click="submitForm" size="medium" icon="fa fa-check"> 保 存
              </el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="修改密码" name="modifyPassword" class="userInfo">
            <el-form :model="modifyPasswordModel" ref="modifyPasswordForm" label-width="80px"
                     :rules="modifyPasswordRules"
                     size="small">
              <el-form-item label="旧密码" prop="oldPassword">
                <el-input v-model="modifyPasswordModel.oldPassword" placeholder="请输入旧密码"
                          show-password/>
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="modifyPasswordModel.newPassword" placeholder="请输入新密码"
                          show-password/>
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input v-model="modifyPasswordModel.confirmPassword" placeholder="请确认密码"
                          show-password/>
              </el-form-item>
            </el-form>
            <div class="bottom">
              <el-button @click="closeProfile" size="medium" icon="fa fa-reply-all"> 关 闭</el-button>
              <el-button type="primary" @click="submitModifyPassword" size="medium" icon="fa fa-check">
                保 存
              </el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-col>
  </el-row>
</template>
<script lang="ts">
import {Component, Ref, Vue} from 'vue-property-decorator';
import {modifyPassword, updateUserInfo} from '@/api/profile';
import {Action, Getter} from 'vuex-class';
import {getById} from '@/api/dept';
import {checkEmailUnique, checkPhoneUnique, getPostListByUserId} from '@/api/user';
import UserAvatar from '@/components/UserAvatar/UserAvatar.vue';
import {log, validateForm} from '@/utils';

@Component({components: {UserAvatar}})
export default class Profile extends Vue {
  @Ref('userInfoForm') private userInfoForm: any;
  @Ref('modifyPasswordForm') private modifyPasswordForm: any;
  @Action('LogOut') private LogOut!: () => Promise<any>;
  @Getter('userInfo') private userInfo!: any;
  @Getter('avatar') private url!: string;
  @Action('setUserInfo') private setUserInfo!: (data) => Promise<any>;

  avatarSize = 128;
  data: any = {};
  activeName = 'userInfo';
  userModel: any = {
    name: '',
    email: '',
    phoneNumber: '',
    sex: ''
  };
  modifyPasswordModel: any = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  };
  userInfoRules: any = {
    name: [
      {required: true, message: '姓名不能为空', trigger: ['blur', 'change']}
    ],
    email: [
      {required: true, message: '邮箱不能为空', trigger: ['blur', 'change']},
      {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']},
      {validator: this.validateEmailUnique, trigger: 'blur'}
    ],
    phoneNumber: [
      {required: true, message: '手机号码不能为空', trigger: 'blur'},
      {
        required: true,
        pattern: /^1[345678]\d{9}$/,//可以写正则表达式
        message: '目前只支持中国大陆的手机号码',
        trigger: ['blur', 'change']
      },
      {validator: this.validatePhoneUnique, trigger: 'blur'}
    ],
    sex: [
      {required: true, message: '性别不能为空', trigger: ['blur', 'change']}
    ]
  };

  /*验证手机号码是否唯一*/
  validatePhoneUnique(rule: any, value: any, callback: any) {
    checkPhoneUnique({
      phoneNumber: value,
      id: this.userModel.id
    }).then((res: any) => {
      if (res.data && res.data === '0') {
        callback();
      } else {
        callback(new Error('手机号码已经存在'));
      }
    }).catch((err: any) => {
      console.log(err);
      callback(new Error('手机号码已经存在'));
    })
  }

  /*验证邮箱是否唯一*/
  validateEmailUnique(rule: any, value: any, callback: any) {
    checkEmailUnique({
      email: value,
      id: this.userModel.id
    }).then((res: any) => {
      if (res.data && res.data === '0') {
        callback();
      } else {
        callback(new Error('邮箱已经存在'));
      }
    }).catch((err: any) => {
      console.log(err);
      callback(new Error('邮箱已经存在'));
    })
  }

  validatePass(rule: any, value: any, callback: any) {
    if (value === '') {
      callback(new Error('请再次输入密码'));
    } else if (value !== this.modifyPasswordModel.newPassword) {
      callback(new Error('两次输入密码不一致!'));
    } else {
      callback();
    }
  }

  modifyPasswordRules: any = {
    oldPassword: [
      {required: true, message: '原密码不能为空', trigger: ['blur']}
    ],
    newPassword: [
      {required: true, message: '新密码不能为空', trigger: ['blur']}
    ],
    confirmPassword: [
      {required: true, message: '确认密码不能为空', trigger: ['blur']},
      {validator: this.validatePass, trigger: 'blur'}
    ],
  };

  file: any = {}; // 当前被选择的图片文件


  handleClick(tab?: any, event?: any) {
    if (this.userInfoForm) {
      this.userModel = Object.assign({}, this.data);
      this.userInfoForm.clearValidate();//将form表单重置
    }
    if (this.modifyPasswordForm) {
      this.modifyPasswordForm.resetFields();//将form表单重置
    }
  }

  submitForm() {
    delete this.userModel.dept;
    delete this.userModel.posts;
    delete this.userModel.avatar;
    updateUserInfo(this.userModel).then((response: any) => {
      this.setUserInfo(response.data).then(() => {
        this.$message.success(response.msg);
      });
      console.log(this.data);
      this.userModel.dept = Object.assign({}, this.data.dept);
      this.userModel.posts = Object.assign({}, this.data.posts);
      this.data = Object.assign({}, this.userModel);
    }).catch((e) => {
      console.log(e);
      validateForm(e, this.modifyPasswordForm, this.modifyPasswordRules);
    });
  }

  handleAvatarSuccess(res: any) {
    delete this.userModel.dept;
    delete this.userModel.posts;
    this.userModel.avatar = res.data.fileName;
    updateUserInfo(this.userModel).then((response: any) => {
      log(response);
      this.setUserInfo(response.data).then(() => {
        this.$message.success(response.msg);
      });
    }).catch((e) => {
      console.log(e);
    });
  }

  submitModifyPassword() {
    modifyPassword({
      'oldPassWord': this.modifyPasswordModel.oldPassword,
      'newPassWord': this.modifyPasswordModel.newPassword
    }).then((response: any) => {
      this.$message.success(response.msg);
      setTimeout(() => {
        this.LogOut().then(() => {
          location.reload();
        }).catch((err: any) => {
          console.log(err);
        });
      }, 1000);
    }).catch((e) => {
      console.log(e);
      validateForm(e, this.modifyPasswordForm, this.modifyPasswordRules);
    });
  }

  closeProfile() {
    this.$store.dispatch('delView', this.$route).catch(reason => console.log(reason));
    this.$router.push({path: '/'}).catch(reason => console.log(reason));
  }

  getData() {
    this.data = this.userInfo;

    this.userModel = Object.assign({}, this.data);
    if (this.data.deptId) {
      getById({'id': this.data.deptId}).then(response => {
        if (response) {
          this.data.dept = response.data;
        }
      }).catch((e) => {
        console.log(e);
      });
    } else {
      this.data.dept = null;
    }

    getPostListByUserId({'id': this.data.id}).then(response => {
      if (response) {
        this.data.posts = response.data;
      }
    }).catch((e) => {
      console.log(e);
    });
  }

  get deptAndPost() {
    let deptName = '无部门';
    let postsName = '无岗位';
    let deptAndPostName;
    if (this.data && this.data.dept && this.data.dept.deptName) {
      deptName = this.data.dept.deptName;
    }
    if (this.data && this.data.posts) {
      postsName = '';
      if (this.data && this.data.posts && this.data.posts.length > 0) {
        this.data.posts.forEach(post => {
          postsName += post.postName + ',';
        });
      }
      if (postsName) {
        postsName = postsName.substr(0, postsName.length - 1);
      } else if (this.data.id === 1) {
        postsName = '超级管理员';
      }
    }
    deptAndPostName = deptName + '/' + postsName;
    if (deptAndPostName.length > 15) {
      deptAndPostName = deptAndPostName.substr(0, 15);
      deptAndPostName += '...';
    }
    return {deptAndPostName: deptAndPostName, title: deptName + '/' + postsName};
  }

  mounted() {
    this.getData();
    setTimeout(() => {
      this.handleClick();
    }, 500);
  }
}
</script>

<style scoped lang="scss">

.box-card {
  .item {
    color: #606266;
    font-size: 14px;
    padding: 10px 10px;
    border-bottom: 1px solid rgb(231, 234, 236);

    .floatLeft {
      float: left;

      .fa {
        margin-right: 5px;
        width: 15px;
        height: 15px;
      }
    }

    .floatRight {
      float: right;
    }

    .user-avatar {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  ul {
    margin: 0;
    padding: 0;
    list-style-type: none;
  }
}

.bottom {
  float: right;
  text-align: center;
}

.col-item {
  margin-bottom: 20px;
}

</style>

